package kuzha.runtime.jadapter;

import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import kuzha.KuzhaObject;
import kuzha.runtime.Converter;

public class FromMapAdapter<K, V> extends AbstractMap<KuzhaObject, KuzhaObject> {
	private final Map<K, V> map;
	private final Class<K> keycls;
	private final Class<V> valcls;
	
	public FromMapAdapter(Map<K, V> map, Class<K> key, Class<V> value) {
		this.map = map;
		this.keycls = key;
		this.valcls = value;
	}
	
	@Override
	public Set<Map.Entry<KuzhaObject, KuzhaObject>> entrySet() {
		return new AbstractSet<Map.Entry<KuzhaObject, KuzhaObject>>() {
			public Iterator<Map.Entry<KuzhaObject, KuzhaObject>> iterator() {
				final Iterator<Map.Entry<K, V>> iter = map.entrySet().iterator();
				return new Iterator<Map.Entry<KuzhaObject, KuzhaObject>>(){
					@Override
					public boolean hasNext() {
						return iter.hasNext();
					}
					@Override
					public Map.Entry<KuzhaObject, KuzhaObject> next() {
						Map.Entry<K, V> ent = iter.next();
						return new AbstractMap.SimpleImmutableEntry<KuzhaObject, KuzhaObject>(
								Converter.toKuzhaObject(ent.getKey()),
								Converter.toKuzhaObject(ent.getValue())
							);
					}
					@Override
					public void remove() {
						iter.remove();
					}
				};
			}
			public int size() {
				return FromMapAdapter.this.map.size();
			}
		};
	}
	
	@Override
	public KuzhaObject put(KuzhaObject key, KuzhaObject value) {
		return Converter.toKuzhaObject(map.put(Converter.cast(keycls, key), Converter.cast(valcls, value)));
	}
}
